//weather.js
const app = getApp();
var util = require("../../utils/util.js");

Page({
  data: {
    text: "",
    weatherisshow: "none",
    isrefresh: false,
    blurnum: 5,
    headershow: true,
    iswhole: true
  },
  onLoad: function(options) {
    this.loadpoetry(this)
    var that = this
    /* 用户是否授权 获取经纬度 */
    wx.getLocation({
      type: 'wgs84', //默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标  
      success: function(res) { //如果用户授权，点击确定，获取所在城市以及经纬度        
        var longitude = res.longitude
        var latitude = res.latitude
        that.loadWeather(longitude, latitude)
        that.setData({
          isshow: true
        })
      },
      fail: function(res) { //如果用户拒绝授权，点击取消，默认显示上海市        
        that.setData({
          currentCity: "上海市",
          isshow: true
        });
        that.loadWeather(121.38206, 31.11325)
      }
    })
    setTimeout(() => {
      that.setData({
        weatherisshow: "block"
      })
    }, 500)
    wx.getSystemInfo({
      success: function (res) {
        let height = res.windowHeight        
        wx.createSelectorQuery().select('.poet_verse').boundingClientRect(function (rect) {
          that.setData({
            //scroll-view高度为屏幕高度减去上一个节点（'.title'）底部的纵坐标，单位为px
            scrollHeight: res.windowHeight - rect.bottom,
            pmHeight: (res.windowHeight - rect.bottom) * 0.2,
            tempHeight: (res.windowHeight - rect.bottom) * 0.4,
            otherHeight: (res.windowHeight - rect.bottom) * 0.4
          })                    
        }).exec()
      }
    })
  },

  loadWeather: function(longitude, latitude) {
    var that = this;
    wx.request({
      url: "https://api.map.baidu.com/telematics/v3/weather?location=" + longitude + "," + latitude + "&output=json&ak=ZenlWcczwXIAsrvdnGvFkdCSTRxWSXep",
      success: function(res) {   
        console.log(res.data)     
        var pm25 = res.data.results[0].pm25;
        var air_quality = ""
        if (pm25 < 50) {
          air_quality = "优"
        } else if (50 <= pm25 && pm25 < 100) {
          air_quality = "良"
        } else if (100 <= pm25 && pm25 < 150) {
          air_quality = "轻度污染"
        } else if (150 <= pm25 && pm25 < 200) {
          air_quality = "中度污染"
        } else if (200 <= pm25 && pm25 < 300) {
          air_quality = "重度污染"
        } else if (pm25 >= 300) {
          air_quality = "严重污染"
        }
        var today = new Date()
        var time_periods = ""
        var desc_periods = ""
        var dayornight = ""
        var bgurl = ""
        var blurnum = ""
        var hours = today.getHours() //获取当前小时数(0-23)
        var day = today.getDate();
        var weekday = "";
        if (today.getDay() == 1) {
          weekday = "周一";
        } else if (today.getDay() == 2) {
          weekday = "周二";
        } else if (today.getDay() == 3) {
          weekday = "周三";
        } else if (today.getDay() == 4) {
          weekday = "周四";
        } else if (today.getDay() == 5) {
          weekday = "周五";
        } else if (today.getDay() == 6) {
          weekday = "周六";
        } else if (today.getDay() == 0) {
          weekday = "周日";
        }
        if (hours == 1 || hours == 2) {
          time_periods = '丑时'
          desc_periods = "万籁俱寂"
        }
        if (hours == 3 || hours == 4) {
          time_periods = '寅时'
          desc_periods = "浮云朝露"
        }
        if (hours == 5 || hours == 6) {
          time_periods = '卯时'
          desc_periods = "旭日破晓"
        }
        if (hours == 7 || hours == 8) {
          time_periods = '辰时'
          desc_periods = "晨曦初露"
        }
        if (hours == 9 || hours == 10) {
          time_periods = '巳时'
          desc_periods = "日出三竿"
        }
        if (hours == 11 || hours == 12) {
          time_periods = '午时'
          desc_periods = "日轮当午"
        }
        if (hours == 13 || hours == 14) {
          time_periods = '未时'
          desc_periods = "午后风和"
        }
        if (hours == 15 || hours == 16) {
          time_periods = '申时'
          desc_periods = "桑榆暮景"
        }
        if (hours == 17 || hours == 18) {
          time_periods = '酉时'
          desc_periods = "薄暮冥冥"
        }
        if (hours == 19 || hours == 20) {
          time_periods = '戊时'
          desc_periods = "华灯初上"
        }
        if (hours == 21 || hours == 22) {
          time_periods = '亥时'
          desc_periods = "笙歌彻夜"
        }
        if (hours == 23 || hours == 0) {
          time_periods = '子时'
          desc_periods = "夜寝夙兴"
        }

        if (hours >= 1 && hours <= 4) {
          dayornight = "凌 晨"          
        }
        if (hours >= 5 && hours <= 8) {
          dayornight = "清 晨"          
        }
        if (hours >= 9 && hours <= 11) {
          dayornight = "上 午"          
        }
        if (hours >= 11 && hours <= 13) {
          dayornight = "正 午"         
        }
        if (hours >= 14 && hours <= 15) {
          dayornight = "晌 午"         
        }
        if (hours >= 16 && hours <= 18) {
          dayornight = "傍 晚"         
        }
        if (hours >= 19 && hours <= 22) {
          dayornight = "夜 晚"          
        }
        if (hours == 23 || hours == 0) {
          dayornight = "深 夜"          
        }  
        var textcolor = "#fff"
        var weather = res.data.results[0].weather_data[0].weather        
        if ((hours >= 0 && hours <= 5) || (hours >= 17 && hours <= 23)){
          bgurl = "/images/weather-bk.png"      //晚上默认为晚上图片
          blurnum = 5
          textcolor = '#fff'
        }
        else{
        if (weather == "小雨" || weather == "中雨" || weather == "大雨" ||  weather.indexOf("雨转") != -1) {    //白天如果是下雨天
            bgurl = "/images/weather-bk2.png"
            blurnum = 0
            textcolor = '#fff'
          }
          else if (weather == "多云" || weather.indexOf("多云转") != -1) {
            //白天如果是多云
            bgurl = "/images/weather-bk3.png"
            blurnum = 5
            textcolor = '#555'
          }
        else if (weather == "阴" || weather == "阴天" || weather.indexOf("阴转") != -1 || weather == "雾天" || weather == "雾" || weather.indexOf("雾转") != -1) {    //白天如果是阴天、雾天
            bgurl = "/images/weather-bk4.png"
            blurnum = 5
            textcolor = '#fff'
          }
          else if (weather == "晴" || weather == "晴天" || weather.indexOf("晴转") != -1) {
            //白天如果是晴天
            bgurl = "/images/weather-bk5.png"
            blurnum = 5
            textcolor = '#333'
          }
          else if (weather == "小雪" || weather == "中雪" || weather == "大雪" || weather == "雪天" || weather.indexOf("雪转") != -1) {
            //白天如果是雪天
            bgurl = "/images/weather-bk6.png"
            blurnum = 5
            textcolor = '#555'
          }
        }        
        var str = (res.data.results[0].weather_data[0].date).split("：")[1]
        var current_temp_str = str.substr(0, str.length - 2)
        var futureWeather = res.data.results[0].weather_data.splice(1)
        var tipslist = res.data.results[0].index.splice(2,1)
        //.splice(1)去掉第一个元素的数组         
        that.setData({
          time_periods: time_periods,
          desc_periods: desc_periods,
          dayornight: dayornight,
          bgurl: bgurl,
          blurnum: blurnum,
          cityname: res.data.results[0].currentCity,
          current_temp: current_temp_str + "°",
          pm25: res.data.results[0].pm25,
          air_quality: air_quality,
          temperature: res.data.results[0].weather_data[0].temperature,
          weather: res.data.results[0].weather_data[0].weather,
          wind: res.data.results[0].weather_data[0].wind,
          futureWeather: futureWeather,
          tipslist: res.data.results[0].index,
          textcolor: textcolor,
          weekday: weekday,
          curdate: res.data.date
        })
      }
    })
  },
  onPullDownRefresh: function(e) {
    var that = this
    this.setData({
      isrefresh: false,
      iswhole: false,
      headershow: true,
    })
    setTimeout(() => {
      wx.stopPullDownRefresh()
      this.loadpoetry(this)
    }, 1000)    
  },
  loadpoetry: function(that) {
    wx.request({
      url: app.globalData.url + '/poem',
      header: {
        'charset': 'utf-8',
        'content-type': 'application/json' // 默认值
      },
      method: 'GET',
      success: function(res) {
        //console.log(res.data)
        var verse_first = res.data.c[0]
        var verse_two = res.data.c[1]
        var verse_last = res.data.c[2]        
        if (verse_last == null) {           //如果只有两句话，第三句为空
          verse_last = ""
        }
        if (verse_two == null) {            //如果第二句为空，显示默认诗歌
          that.setData({
            verse_first: "闲来垂钓碧溪上",
            verse_two: "忽复乘舟梦日边",
            verse_last: "",
            key: res.data.key,
            iswhole: false
          })
        }
        else{
          that.setData({
            verse_first: verse_first,
            verse_two: verse_two,
            verse_last: verse_last,
            key: res.data.key,
            iswhole: false
          })
        }        
      }
    })
  },
  showpoem: function (e) {
    var that = this
    this.setData({
      headershow: false,
      iswhole: true,
      isrefresh: true
    })
    var poem_key = e.target.dataset.key
    if (poem_key == "Default"){
      this.setData({
        title: "行路难·其一",
        author: "李白",
        content: "金樽清酒斗十千，玉盘珍羞直万钱。停杯投箸不能食，拔剑四顾心茫然。欲渡黄河冰塞川，将登太行雪满山。闲来垂钓碧溪上，忽复乘舟梦日边。行路难！行路难！多岐路，今安在？长风破浪会有时，直挂云帆济沧海"
      })
    }
    else{
      wx.request({
        url: app.globalData.url + '/poem',
        header: {
          'charset': 'utf-8',
          'content-type': 'application/json' // 默认值
        },
        method: 'POST',
        data: {
          key: poem_key
        },
        success: function (res) {
          that.setData({
            title: res.data.title,
            author: res.data.author,
            content: res.data.content
          })
        },
        fail: function (res) {
          console.log("失败")
        }
      })
    }    
  },
  hidepoem: function (e) {
    this.setData({
      headershow: true,
      iswhole: false,
      isrefresh: false
    })
  },
  onShareAppMessage: function () { //用户点击右上角分享   
    return {
      title: '冷暖自知', // 分享标题
      desc: '天气页面分享', // 分享描述
      path: 'pages/weather/weather' // 分享路径
    }
  },
})